﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.ComponentModel;
using ToolBoxPro;
/// <summary>
/// Summary description for Order
/// </summary>

namespace LinqObj
{
    public partial class Order : Notifications
    {
        public static ToolboxDataContext _context = new ToolboxDataContext();

        public const string STATUS_PROPOSE = "propose";
        public const string STATUS_COMPLETE = "done";
        public const string STATUS_ORDERED = "ordered";
        public const string PREFIX = "service_";
        public const string DUE_PREFIX = "due_";

        public static List<Order> LoadOrderList(int propertyID, string campaignStatus)
        {
            int intStatus = FormContract.FindKey(Campaign.CampaignStatusLookups, campaignStatus).Value;

            int campaignID = (from _campaign in _context.GetTable<Campaign>()
                              where _campaign.campaign_status == intStatus && _campaign.property_id == propertyID
                              select _campaign.campaign_id).SingleOrDefault();
            if (campaignID <= 0)
                return null;
            IEnumerable<Order> orders = from _order in _context.GetTable<Order>()
                                        where _order.campaign_id == campaignID
                                        select _order;

            return orders.ToList();
        }

        public static List<Order> LoadOrderByCampaignID(int campaignID)
        {
            return (from order in _context.GetTable<Order>()
                    where order.campaign_id == campaignID
                    select order).ToList();
        }

        public bool SendOrder()
        {
            try
            {
                Notifications email = new Notifications(this);
                email.SendEmail();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }


        public new bool BeforeSend()
        {
            Console.WriteLine(this.email_sent);
            if (this.email_sent)
            {
                return false;
            }
            else
                return true;
        }

        public new void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            base.SendCompletedCallback(sender, e);
            if (this.mailSent)
                this.email_sent = true;
            try
            {
                _context.SubmitChanges();
            }
            catch (Exception ex)
            {
                _context.ChangeConflicts.Clear();
                _context.SubmitChanges();
            }
        }


        public void setAgentID(int agentID)
        {
            if (agentID == 0)
            {
                this.Agent = null;
            }
            else
            {
                if (this.agent_id == agentID)
                    return;
                this.Agent = (from _a in _context.GetTable<Agent>()
                              where _a.agent_id == agentID
                              select _a).First<Agent>();
            }
        }
    }
}
    //public static IEnumerable<Order> GetExisingOrders(int campaignID)

    //    public static bool SaveOrderList(IDbConnection conn, List<Order> orderList, int campaignID)
    //    {
    //        string sql_script =
    //                       @"   if not exists (select * from [order]
    //                                    where service_id = @serviceID and campaign_id = @campaignID and order_status<>@orderStatus)
    //                                insert into [order](service_id, campaign_id)
    //                                values(@serviceID, @campaignID);
    //                                else
    //                                    update [order]
    //                                        set due_date = @dueDate
    //                                    where service_id = @serviceID and campaign_id = @campaignID and order_status<>@orderStatus;                                       
    //                                ";
    //        IDbTransaction tran = conn.BeginTransaction();

    //        int orderID = 0;
    //        string newServiceList = "";
    //        try
    //        {
    //            foreach (Order order in orderList)
    //            {
    //                IDbCommand cmd = conn.CreateCommand();
    //                cmd.CommandText = sql_script;
    //                IDbDataParameter param = cmd.CreateParameter();
    //                param.ParameterName = "@serviceID";
    //                param.DbType = DbType.Int32;
    //                param.Value = order.serviceID;
    //                cmd.Parameters.Add(param);

    //                param = cmd.CreateParameter();
    //                param.ParameterName = "@orderStatus";
    //                param.DbType = DbType.String;
    //                param.Value = Order.STATUS_COMPLETE;
    //                cmd.Parameters.Add(param);

    //                param = cmd.CreateParameter();
    //                param.ParameterName = "@campaignID";
    //                param.DbType = DbType.Int32;
    //                param.Value = campaignID;
    //                cmd.Parameters.Add(param);

    //                param = cmd.CreateParameter();
    //                param.ParameterName = "@dueDate";
    //                param.DbType = DbType.DateTime;
    //                param.Value = order.dueDate;
    //                cmd.Parameters.Add(param);

    //                cmd.Transaction = tran;
    //                cmd.ExecuteNonQuery();

    //                //cmd.CommandText = @"select IDENT_CURRENT('[order]') as order_id";

    //                //order.OrderID = Convert.ToInt32(cmd.ExecuteScalar().ToString());
    //                newServiceList = newServiceList + "," + order.serviceID;
    //            }
    //            if (newServiceList != "")
    //            {
    //                newServiceList = newServiceList.Remove(0, 1);
    //                sql_script = "delete from [order] where campaign_id = @campaignID and order_status <> @orderStatus and service_id not in (" + newServiceList + ")";
    //            }
    //            else
    //                sql_script = "delete from [order] where campaign_id = @campaignID and order_status <> @orderStatus";
    //            IDbCommand deleteCmd = conn.CreateCommand();
    //            IDbDataParameter para = deleteCmd.CreateParameter();
    //            para.DbType = DbType.Int32;
    //            para.Value = campaignID;
    //            para.ParameterName = "@campaignID";
    //            deleteCmd.Parameters.Add(para);

    //            para = deleteCmd.CreateParameter();
    //            para.DbType = DbType.String;
    //            para.Value = Order.STATUS_COMPLETE;
    //            para.ParameterName = "@orderStatus";
    //            deleteCmd.Parameters.Add(para);

    //            deleteCmd.CommandText = sql_script;
    //            deleteCmd.Transaction = tran;
    //            deleteCmd.ExecuteNonQuery();

    //            tran.Commit();
    //            return true;
    //        }
    //        catch (Exception error)
    //        {
    //            tran.Rollback();
    //            throw (error);
    //        }
    //    }
    //    private bool urgentMark;
    //    private string serviceName;
    //    private decimal serviceCharge;
    //    private int orderID;
    //    //private int propertyID;
    //    //private int userID;
    //    private int serviceID;
    //    private DateTime orderDate;
    //    private string orderStatus;
    //    private bool applyDiscount;
    //    private int campaignID;
    //    private DateTime dueDate;
    //    private string email;




    //    //private int agentID;

    //    public int OrderID { get { return this.orderID; } set { this.orderID = value; } }
    //    //public int PropertyID { get { return this.propertyID; } set { this.propertyID = value; } }
    //    //public int UserID { get { return this.userID; } set { this.userID = value; } }
    //    public int ServiceID { get { return this.serviceID; } set { this.serviceID = value; } }
    //    public DateTime OrderDate { get { return this.orderDate; } }
    //    public string OrderStatus { get { return this.orderStatus; } set { this.orderStatus = value; } }
    //    public bool ApplyDiscount { get { return this.applyDiscount; } set { this.applyDiscount = value; } }
    //    public int CampaignID { get { return this.campaignID; } }
    //    //public int AgentID { get { return this.agentID; } set { this.agentID = value; } }
    //    public string ServiceName { get { return this.serviceName; } set { this.serviceName = value; } }
    //    public decimal ServiceCharge { get { return this.serviceCharge; } set { this.serviceCharge = value; } }
    //    public bool UrgentMark { get { return this.urgentMark; } set { this.urgentMark = value; } }
    //    public DateTime DueDate { get { return this.dueDate; } set { this.dueDate = value; } }
    //    public string Email { get { return this.email; } set { this.email = value; } }



    //    public Order()
    //    {


    //    }

    //    public void UpdateOrder(IDbConnection conn, Order _order)
    //    {
    //        //            string sql_script = @"update [order]
    //        //                                    set order_status = @orderStatus
    //        //                                where order";

    //    }

    //    public bool SendOrder()
    //    {
    //        string _mailSubject = "New order:" + this.serviceName + "";
    //        Notifications.SendMailMessage(this.email, _mailSubject, "Hi", true);
    //        return true;
    //    }

    //    public static bool SaveOrderList(IDbConnection conn, List<Order> orderList, int campaignID)
    //    {
    //        string sql_script =
    //                       @"   if not exists (select * from [order]
    //                                    where service_id = @serviceID and campaign_id = @campaignID and order_status<>@orderStatus)
    //                                insert into [order](service_id, campaign_id)
    //                                values(@serviceID, @campaignID);
    //                                else
    //                                    update [order]
    //                                        set due_date = @dueDate
    //                                    where service_id = @serviceID and campaign_id = @campaignID and order_status<>@orderStatus;                                       
    //                                ";
    //        IDbTransaction tran = conn.BeginTransaction();

    //        int orderID = 0;
    //        string newServiceList = "";
    //        try
    //        {
    //            foreach (Order order in orderList)
    //            {
    //                IDbCommand cmd = conn.CreateCommand();
    //                cmd.CommandText = sql_script;
    //                IDbDataParameter param = cmd.CreateParameter();
    //                param.ParameterName = "@serviceID";
    //                param.DbType = DbType.Int32;
    //                param.Value = order.serviceID;
    //                cmd.Parameters.Add(param);

    //                param = cmd.CreateParameter();
    //                param.ParameterName = "@orderStatus";
    //                param.DbType = DbType.String;
    //                param.Value = Order.STATUS_COMPLETE;
    //                cmd.Parameters.Add(param);

    //                param = cmd.CreateParameter();
    //                param.ParameterName = "@campaignID";
    //                param.DbType = DbType.Int32;
    //                param.Value = campaignID;
    //                cmd.Parameters.Add(param);

    //                param = cmd.CreateParameter();
    //                param.ParameterName = "@dueDate";
    //                param.DbType = DbType.DateTime;
    //                param.Value = order.dueDate;
    //                cmd.Parameters.Add(param);

    //                cmd.Transaction = tran;
    //                cmd.ExecuteNonQuery();

    //                //cmd.CommandText = @"select IDENT_CURRENT('[order]') as order_id";

    //                //order.OrderID = Convert.ToInt32(cmd.ExecuteScalar().ToString());
    //                newServiceList = newServiceList + "," + order.serviceID;
    //            }
    //            if (newServiceList != "")
    //            {
    //                newServiceList = newServiceList.Remove(0, 1);
    //                sql_script = "delete from [order] where campaign_id = @campaignID and order_status <> @orderStatus and service_id not in (" + newServiceList + ")";
    //            }
    //            else
    //                sql_script = "delete from [order] where campaign_id = @campaignID and order_status <> @orderStatus";
    //            IDbCommand deleteCmd = conn.CreateCommand();
    //            IDbDataParameter para = deleteCmd.CreateParameter();
    //            para.DbType = DbType.Int32;
    //            para.Value = campaignID;
    //            para.ParameterName = "@campaignID";
    //            deleteCmd.Parameters.Add(para);

    //            para = deleteCmd.CreateParameter();
    //            para.DbType = DbType.String;
    //            para.Value = Order.STATUS_COMPLETE;
    //            para.ParameterName = "@orderStatus";
    //            deleteCmd.Parameters.Add(para);

    //            deleteCmd.CommandText = sql_script;
    //            deleteCmd.Transaction = tran;
    //            deleteCmd.ExecuteNonQuery();

    //            tran.Commit();
    //            return true;
    //        }
    //        catch (Exception error)
    //        {
    //            tran.Rollback();
    //            throw (error);
    //        }
    //    }

    //    public static List<Order> LoadOrderList(IDbConnection conn, int propertyID, string campaignStatus)
    //    {
    //        string sql_script =
    //                            @"select order_id, order_date, order_status, campaign_id, urgent_mark, S.service_id, due_date, R.supplier_email from [order] as O
    //                                    left join [service] as S
    //                                            on S.service_id = O.service_id
    //                                        left join [supplier] as R
    //                                                on S.supplier_id = R.supplier_id
    //                                        where campaign_id = (select top 1 campaign_id from campaign where property_id = @propertyID and campaign_status = @campaignStatus)";

    //        List<Order> orderList = new List<Order>();

    //        IDbCommand cmd = conn.CreateCommand();
    //        cmd.CommandText = sql_script;

    //        IDbDataParameter param = cmd.CreateParameter();
    //        param.ParameterName = "@propertyID";
    //        param.DbType = DbType.Int32;
    //        param.Value = propertyID;
    //        cmd.Parameters.Add(param);

    //        param = cmd.CreateParameter();
    //        param.ParameterName = "@campaignStatus";
    //        param.DbType = DbType.String;
    //        param.Value = campaignStatus;
    //        cmd.Parameters.Add(param);

    //        IDataReader dr = cmd.ExecuteReader();

    //        while (dr.Read())
    //        {
    //            Order order = new Order();
    //            order.orderID = Convert.ToInt32(dr["order_id"].ToString());
    //            order.orderDate = Convert.ToDateTime(dr["order_date"]);
    //            order.orderStatus = dr["order_status"].ToString();
    //            order.campaignID = Convert.ToInt32(dr["campaign_id"]);
    //            order.urgentMark = Convert.ToBoolean(dr["urgent_mark"]);
    //            order.serviceID = Convert.ToInt32(dr["service_id"]);
    //            if (!dr.IsDBNull(6))
    //                order.dueDate = dr.GetDateTime(6);
    //            order.email = dr.GetString(7);
    //            orderList.Add(order);

    //        }
    //        return orderList;


    //    }